package com.itheima.controller;

import com.itheima.domain.vo.Result;

import com.itheima.oss.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author:篍
 * @Date: 2025/07/12 17:02
 * @Description:
 */
@RestController
@RequestMapping
@Slf4j
public class FileController {

    @Autowired
    AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("/upload")
    public Result fileUpload(MultipartFile file) throws Exception {
        log.warn("file:{}",file);
        if(Objects.nonNull(file)&&!file.isEmpty()){
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
            log.warn("uniqueFileName={}",uniqueFileName);
            // 上传文件
            String url = aliyunOSSOperator.upload(file.getBytes(), uniqueFileName);
            return Result.success(url);
        }
        return Result.error("上传失败");
    }
}
